package cn.aws360.boot.extend.open.biz.service.impl;

import cn.aws360.boot.extend.open.api.constant.enums.ChatApiEnum;
import cn.aws360.boot.extend.open.api.pojo.properties.OpenProperties;
import cn.aws360.boot.extend.open.biz.helper.ApiHelper;
import cn.aws360.boot.extend.open.biz.service.ChatService;
import cn.hutool.core.util.ObjectUtil;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;

/**
 * @author junnan
 */
@Service
@RequiredArgsConstructor
public class ChatServiceImpl implements ChatService {

    private final OpenProperties openProperties;

    @Override
    public String getAiChatRes(String input) {
        JSONObject paramJson = new JSONObject().fluentPut("prompt", input);
        JSONObject resultJson = ApiHelper.getApiResult4Ai(openProperties, ChatApiEnum.AI.getUrl(), paramJson);
        if (ObjectUtil.isNotNull(resultJson)) {
            JSONArray choicesArr = resultJson.getJSONArray("choices");
            if (choicesArr != null && choicesArr.size() > 0) {
                return choicesArr.getJSONObject(0).getString("text");
            }
        }
        return null;
    }

    @Override
    public String getTlChatRes(String input) {
        JSONObject paramJson = new JSONObject()
                .fluentPut("reqType", 0)
                .fluentPut("perception", new JSONObject()
                        .fluentPut("inputText", new JSONObject().fluentPut("text", input)));
        JSONObject resultJson = ApiHelper.getApiResult4Tl(openProperties, ChatApiEnum.TL.getUrl(), paramJson);
        if (ObjectUtil.isNotNull(resultJson)) {
            JSONArray resultsArr = resultJson.getJSONArray("results");
            if (resultsArr != null && resultsArr.size() > 0) {
                JSONObject itemJson = resultsArr.getJSONObject(0);
                String outType = itemJson.getString("resultType");
                return itemJson.getJSONObject("values").getString(outType);
            }
        }
        return null;
    }

    @Override
    public String getChatRes(String type, String input) {
        ChatApiEnum apiEnum = ChatApiEnum.getEnum(type);
        if (apiEnum != null) {
            switch (apiEnum) {
                case AI:
                    return getAiChatRes(input);
                case TL:
                    return getTlChatRes(input);
                default:
                    break;
            }
        }
        return null;
    }

}
